/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.serialize;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;

/**
 * @author creativor
 * 
 */
class Deserializer {

	private final byte[] bytes;
	private byte version;
	private final ByteArrayInputStream bais;
	private final DataInputStream dis;
	private Object obj;
	private SerializableType<?> objType;

	/**
	 * @param bytes
	 */
	Deserializer(final byte[] bytes) {
		this.bytes = bytes;
		bais = new ByteArrayInputStream(bytes);
		dis = new DataInputStream(bais);
	}

	/**
	 * @return
	 * @throws IOException
	 * @throws SerializeFormatException
	 */
	public Object deseriaize() throws SerializeFormatException {
		try {
			readHeader();
			readThisObject();
			readFields();
		} catch (final EOFException e) {
			throw new SerializeFormatException(e.getMessage());

		} catch (final IOException e) {
			// Impossible, ignore it.
		} catch (final UnsupportedTypeException e) {
			throw new SerializeFormatException("Object type format is wrong", e);
		}
		return this.obj;
	}

	private void readFields() throws IOException, SerializeFormatException {
		this.objType.readFields(this.dis, obj);
	}

	private void readHeader() throws SerializeFormatException, IOException {

		if (dis.readShort() != Constants.MAGIC_NUMBER)
			throw new SerializeFormatException("Magic number is wrong");
		this.version = dis.readByte();
	}

	/**
	 * @throws IOException
	 * @throws UnsupportedTypeException
	 * @throws SerializeFormatException
	 * 
	 */
	private void readThisObject() throws UnsupportedTypeException, IOException,
			SerializeFormatException {
		this.objType = Types.getType(dis.readByte());
		this.obj = this.objType.read(dis);
	}
}